﻿using Configuration.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HTUI.Cher_WorkTime
{

    public partial class ErrorMegForm : Form
    {
        // 错误码映射表
        private static readonly Dictionary<int, string> ErrorCodeMap = new Dictionary<int, string>{
            { 64, "手环绿灯" },
            { 32, "手环黄灯" },
            { 16, "手环红灯" },
            { 8,  "呼叫主管" },
            { 4,  "品质异常" },
            { 2,  "设备异常" },
            { 1,  "物料短缺" }
        };
        // 将数值解析为错误信息列表（按位解析）
        private List<string> ParseErrorCodes(int value)
        {
            var errors = new List<string>();
            foreach (var code in ErrorCodeMap.Keys.OrderByDescending(k => k))
            {
                if (value >= code)
                {
                    errors.Add(ErrorCodeMap[code]);
                    value -= code;
                }
            }
            return errors;
        }

        public ErrorMegForm()
        {
            InitializeComponent();
            DateTimePicker dtpstart = new DateTimePicker();
            DateTimePicker dtpend = new DateTimePicker();
            dtpstart.Width = 130;
            dtpstart.Format = DateTimePickerFormat.Long;
            dtpstart.Value = DateTime.Now;
            ToolStripControlHost host1 = new ToolStripControlHost(dtpstart);
            toolStrip1.Items.Insert(0, host1);

            dtpend.Width = 130;
            dtpend.Format = DateTimePickerFormat.Long;
            dtpend.Value = DateTime.Now;
            ToolStripControlHost host = new ToolStripControlHost(dtpend);
            toolStrip1.Items.Insert(0, host);

            string sqlString = "SELECT * FROM ZB_LINE_DATA D ORDER BY D.SNAME, D.SDATE";
            DataTable table = CommonTools.RunSqlHelper.Query(BGO.UniversalConnectionString, sqlString);
            List<DataRecord> list = CherPublicTools.CherTool.TableToListModel<DataRecord>(table).ToList();
            List<AlarmRecord> records = GenerateAlarms(list);
            DataTable resultTable = CherPublicTools.CherTool.ListToTable(records);
            dataGridView1.DataSource = resultTable;
            //ExcelHelper.ExportToExcel(resultTable);
        }

        public class DataRecord
        {
            public string SNAME { get; set; }
            public DateTime SDATE { get; set; }
            public string SDATA { get; set; }
        }

        public class AlarmRecord
        {
            public string DeviceIP { get; set; }
            public string Time { get; set; }
            public string ChangeDetails { get; set; }
        }

        public List<AlarmRecord> GenerateAlarms(List<DataRecord> records)
        {
            var alarms = new List<AlarmRecord>();
            if (records == null || records.Count < 2) return alarms;

            for (int i = 1; i < records.Count; i++)
            {
                var prev = records[i - 1];
                var current = records[i];

                var prevValues = ParseHexData(prev.SDATA);
                var currentValues = ParseHexData(current.SDATA);

                if(current.SDATA == "4040404040404040404040400000")
                {
                    continue;
                }
                // 逐工位对比错误状态
                var changes = new List<string>();
                for (int j = 0; j < prevValues.Count; j++)
                {
                    var prevErrors = ParseErrorCodes(prevValues[j]);
                    var currentErrors = ParseErrorCodes(currentValues[j]);

                    // 检查新增或消失的错误状态
                    var newErrors = currentErrors.Except(prevErrors).ToList();
                    var resolvedErrors = prevErrors.Except(currentErrors).ToList();

                    if (newErrors.Any() || resolvedErrors.Any())
                    {
                        var changeDesc = new StringBuilder();
                        changeDesc.Append($"工位 {j + 1}: ");
                        if (newErrors.Any())
                            changeDesc.Append($"新增 [{string.Join(", ", newErrors)}] ");
                        if (resolvedErrors.Any())
                            changeDesc.Append($"解除 [{string.Join(", ", resolvedErrors)}]");

                        changes.Add(changeDesc.ToString());
                    }
                }

                // 生成报警记录
                if (changes.Any())
                {
                    alarms.Add(new AlarmRecord
                    {
                        DeviceIP = current.SNAME,
                        Time = current.SDATE.ToString("yyyy/MM/dd HH:mm:ss"),
                        ChangeDetails = string.Join("\n", changes)
                        //ChangeDetails = $"与前一记录（{prev.SNAME}，{prev.SDATE:yyyy/MM/dd HH:mm:ss}）对比：\n" +
                        //               string.Join("\n", changes)
                    });
                }
            }
            return alarms;
        }

        // 解析十六进制字符串为十进制数值列表
        private List<int> ParseHexData(string hexData)
        {
            var values = new List<int>();

            for (int i = 0; i < hexData.Length; i += 2)
            {
                string hexByte = hexData.Substring(i, 2);
                if (int.TryParse(hexByte, NumberStyles.HexNumber, null, out int value))
                    values.Add(value);
                else
                    throw new ArgumentException($"Invalid hex value: {hexByte}");
            }
            return values;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            DateTimePicker dtpstart = new DateTimePicker();
            DateTimePicker dtpend = new DateTimePicker();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExcelHelper.ExportToExcel(dataGridView1.DataSource as DataTable);
        }

        private void btnQueryRecord_Click(object sender, EventArgs e)
        {
            string sqlString = "SELECT Q.ID,\n" +
            "       Q.CONTENT       \"内容\",\n" +
            "       Q.STATE         \"状态\",\n" +
            "       Q.CREATE_TIME   \"创建时间\",\n" +
            "       Q.DONE_TIME     \"完成时间\",\n" +
            "       Q.FIRST_WORKID  \"一级处理\",\n" +
            "       Q.SECOND_WORKID \"二级处理\"\n" +
            "  FROM QC_ALARM2 Q";
            DataTable table = CommonTools.RunSqlHelper.Query(BGO.UniversalConnectionString, sqlString);
            dataGridView1.DataSource = table;

        }
    }
}
